package com.gs.m_home.model

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.gs.common.API
import com.gs.common.callback.HttpCallback
import com.gs.common.callback.impl.CommonHttpCallback
import com.gs.common.constant.HttpCode
import com.gs.common.constant.StateCode
import com.gs.common.data.CartData
import com.gs.common.global.GlobalVariables
import com.gs.common.sqlite.UserSqliteOpenHelper
import okhttp3.Call
import okhttp3.Response
import org.json.JSONObject
import java.net.ConnectException
import java.net.SocketTimeoutException

class CartModel(context: Context) {

    private val api by lazy { API.getInstance() }

    fun updateCartGoodData(username: String, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.updateCartGoodData(username, object : HttpCallback{
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.header("Set-Cookie")
                Log.d("cookies", "$cookies")
                val resultJSON = JSONObject(result)
                Log.d("result", result)
                Log.d("code", "${resultJSON["code"]}")
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    val msgJSON = JSONObject(resultJSON["msg"].toString())
                    val goodsListString = msgJSON["list"].toString()
                    val gson = Gson()
                    val cartDataList =
                        gson.fromJson(goodsListString, Array<CartData>::class.java).toList()
                    Log.d("cartData", cartDataList.toString())
                    GlobalVariables.cartDataList = cartDataList
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                block.invoke(StateCode.STATE_FAILED)
            }

            override fun onError(call: Call, e: Exception) {
                when(e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }
                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }
                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }

        })
    }

    fun addGoodSoldCount(orderId: Int, goodId: Int, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.addGoodSoldCount(orderId, goodId, CommonHttpCallback(block))
    }

    fun subtractGoodSoldCount(orderId: Int, goodId: Int, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.subtractGoodSoldCount(orderId, goodId, CommonHttpCallback(block))
    }

    fun deleteGood(orderId: Int, goodId: Int, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.deleteGoodFromCart(orderId, goodId, CommonHttpCallback(block))
    }

    fun getCartOrderId(username: String, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.getCartOrderId(username, object : HttpCallback{
            override fun onSuccess(call: Call, result: String, response: Response) {
                val cookies = response.header("Set-Cookie")
                Log.d("cookies", "$cookies")
                val resultJSON = JSONObject(result)
                Log.d("result", result)
                Log.d("code", "${resultJSON["code"]}")
                if (resultJSON["code"] == HttpCode.SUCCESS_CODE) {
                    GlobalVariables.curCartOrderId = resultJSON["cartOrderId"].toString().toInt()
                    block.invoke(StateCode.STATE_SUCCESS)
                    return
                }
                block.invoke(StateCode.STATE_FAILED)
            }

            override fun onError(call: Call, e: Exception) {
                when(e) {
                    is ConnectException -> {
                        block.invoke(StateCode.NETWORK_ERROR)
                    }
                    is SocketTimeoutException -> {
                        block.invoke(StateCode.SERVER_ERROR)
                    }
                    else -> {
                        block.invoke(StateCode.UNKNOWN_ERROR)
                    }
                }
            }

        })
    }

    fun payOrder(username: String, block: (Int) -> Unit) {
        block.invoke(StateCode.STATE_LOADING)
        api.payOrder(username, CommonHttpCallback(block))
    }

    companion object{
        private var instance: CartModel? = null
        fun getInstance(context: Context): CartModel {
            if (instance == null) {
                synchronized(this::class) {
                    if (instance == null) {
                        instance = CartModel(context)
                    }
                }
            }
            return instance!!
        }
    }

}